#include "LinkList_kernel.h"

int LinkList_kernel_init(LinkList_t **head){
    if(*head!=NULL){
        return -1;
    }
    (*head) = (LinkList_t*)malloc(sizeof(LinkList_t));
    if(head==NULL){
        LOG("LinkList create failed\n");
        return -1;
    }
    INIT_LIST_HEAD(&(*head)->list);
    LOG("LinkList create success\n");
    return 0;
}

int LinkList_kernel_headinsert(LinkList_t * head,int data){
    if(head == NULL){
        return -1;
    }
    LinkList_t * p = (LinkList_t *)malloc(sizeof(LinkList_t));
    if(p==NULL){
        LOG("item create failed\n");
        return -1;
    }
    INIT_LIST_HEAD(&p->list);
    p->data = data;
    list_add(&p->list,&head->list);
    return 0;
}

int LinkList_kernel_tailinsert(LinkList_t * head,int data){
    if(head == NULL){
        return -1;
    }
    LinkList_t * p = (LinkList_t *)malloc(sizeof(LinkList_t));
    if(p==NULL){
        LOG("item create failed\n");
        return -1;
    }
    INIT_LIST_HEAD(&p->list);
    p->data = data;
    list_add_tail(&p->list,&head->list);
    return 0;
}

int LinkList_kernel_delitem(LinkList_t *head,int index){
    if(head == NULL){
        return -1;
    }
    struct list_head *pos = NULL;
    int i = 0;
    list_for_each(pos,&head->list){
        if(i==index){
            LinkList_t * item = list_entry(pos,LinkList_t,list);
            if(item == NULL){
                LOG("the item is not exist\n");
                return -1;
            }
            LOG("data:%d\n",item->data);
            list_del(&item->list);
            free(item);
            item = NULL;
            break;
        }
        i++;
    }
}

int LinkList_kernel_destory(LinkList_t *head){
    if(head == NULL){
        return -1;
    }
    //使用安全遍历，避免遇到已删除的节点时无法遍历下去
    struct list_head * pos = NULL;
    struct list_head * n = NULL;
    list_for_each_safe(pos,n,&head->list){
        LinkList_t * item = list_entry(pos,LinkList_t,list);
        if(item != NULL){
            list_del(&item->list);
            free(item);
            item = NULL;
        }
    }
    return 0;
}

int LinkList_kernel_select(LinkList_t *head){
    if(head == NULL){
        return -1;
    }
    //定义一个小结构体指针用于查找链表item的结构体
    struct  list_head * pos = NULL;
    LOG("list data:\n");
    int i = 0;
    list_for_each(pos,&head->list){
        //使用list_entry 找到小结构体所属的链表结构体的入口地址
        LinkList_t * item = list_entry(pos,LinkList_t,list);
        if(item==NULL){
            LOG("item is not exist");
            return -1;
        }
        printf("[%d]%d ->",i,item->data);
        i++;
    }
    printf("\n");
    return 0;
}